package com.sws.models;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("roleForUserDao")
@Transactional
public class RoleForUserDao {
	
	private SessionFactory sessionFactory;
	
	@Autowired(required=true)
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
	
	@Transactional(readOnly = false)
	public void saveRole(RoleForUser roleForUser) {
		sessionFactory.getCurrentSession().save(roleForUser);
	}
	
	@Transactional(readOnly = false)
	public void updateRole(RoleForUser roleForUser) {
		sessionFactory.getCurrentSession().update(roleForUser);
	}
	
	@Transactional(readOnly = true)
	public RoleForUser getRoleByUser(User user) {
		List<RoleForUser> roleList = 
			(List<RoleForUser>)sessionFactory.getCurrentSession().createCriteria(RoleForUser.class).add(Restrictions.eq("user",user)).list();
		
		if (roleList != null && roleList.size() > 0)
		{
			return roleList.get(0);
		}
		else
			return null;
	}

}
